"use client";

import { useState, useEffect } from "react";
import Link from "next/link";
import { Button } from "@repo/ui/button";
import styles from "./page.module.css";

// 模拟实时数据
const mockRealTimeData = {
  onlineUsers: 1247,
  activeOrders: 89,
  revenue: 15678.50,
  systemLoad: 67.3
};

// 模拟股票数据
const mockStockData = [
  { symbol: "AAPL", price: 185.42, change: 2.34, changePercent: 1.28 },
  { symbol: "GOOGL", price: 142.56, change: -1.23, changePercent: -0.85 },
  { symbol: "MSFT", price: 378.85, change: 5.67, changePercent: 1.52 },
  { symbol: "TSLA", price: 248.50, change: -3.21, changePercent: -1.28 }
];

// 模拟聊天消息
const mockChatMessages = [
  { id: 1, user: "用户A", message: "这个商品什么时候发货？", time: "14:30" },
  { id: 2, user: "客服", message: "您好，预计明天发货", time: "14:31" },
  { id: 3, user: "用户B", message: "有优惠活动吗？", time: "14:32" },
  { id: 4, user: "客服", message: "是的，现在有满减活动", time: "14:33" }
];

export default function RealtimePage() {
  const [currentTime, setCurrentTime] = useState(new Date());
  const [realTimeData, setRealTimeData] = useState(mockRealTimeData);
  const [stockData, setStockData] = useState(mockStockData);
  const [chatMessages, setChatMessages] = useState(mockChatMessages);
  const [newMessage, setNewMessage] = useState("");
  const [isConnected, setIsConnected] = useState(true);
  const [renderTime, setRenderTime] = useState(new Date());

  // 更新时间
  useEffect(() => {
    const timer = setInterval(() => {
      setCurrentTime(new Date());
    }, 1000);

    return () => clearInterval(timer);
  }, []);

  // 模拟实时数据更新
  useEffect(() => {
    const dataTimer = setInterval(() => {
      setRealTimeData(prev => ({
        onlineUsers: prev.onlineUsers + Math.floor(Math.random() * 10) - 5,
        activeOrders: prev.activeOrders + Math.floor(Math.random() * 5) - 2,
        revenue: prev.revenue + (Math.random() * 100 - 50),
        systemLoad: Math.max(0, Math.min(100, prev.systemLoad + (Math.random() * 10 - 5)))
      }));
    }, 3000);

    return () => clearInterval(dataTimer);
  }, []);

  // 模拟股票数据更新
  useEffect(() => {
    const stockTimer = setInterval(() => {
      setStockData(prev => prev.map(stock => ({
        ...stock,
        price: stock.price + (Math.random() * 2 - 1),
        change: stock.change + (Math.random() * 0.5 - 0.25),
        changePercent: ((stock.change + (Math.random() * 0.5 - 0.25)) / stock.price) * 100
      })));
    }, 2000);

    return () => clearInterval(stockTimer);
  }, []);

  // 发送消息
  const sendMessage = () => {
    if (newMessage.trim()) {
      const message = {
        id: chatMessages.length + 1,
        user: "我",
        message: newMessage,
        time: currentTime.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
      };
      setChatMessages(prev => [...prev, message]);
      setNewMessage("");
    }
  };

  // 模拟连接状态
  const toggleConnection = () => {
    setIsConnected(!isConnected);
  };

  return (
    <div className={styles.container}>
      <header className={styles.header}>
        <h1>实时数据监控</h1>
        <div className={styles.headerInfo}>
          <p>当前时间: {currentTime.toLocaleString('zh-CN')}</p>
          <div className={styles.connectionStatus}>
            <span className={`${styles.statusDot} ${isConnected ? styles.connected : styles.disconnected}`}></span>
            <span>{isConnected ? '已连接' : '已断开'}</span>
            <Button appName="web" onClick={toggleConnection}>
              {isConnected ? '断开连接' : '重新连接'}
            </Button>
          </div>
        </div>
      </header>

      <main className={styles.main}>
        {/* 实时统计 */}
        <section className={styles.statsSection}>
          <h2>实时统计</h2>
          <div className={styles.statsGrid}>
            <div className={styles.statCard}>
              <h3>在线用户</h3>
              <p className={styles.statValue}>{realTimeData.onlineUsers}</p>
              <span className={styles.statLabel}>人</span>
            </div>
            <div className={styles.statCard}>
              <h3>活跃订单</h3>
              <p className={styles.statValue}>{realTimeData.activeOrders}</p>
              <span className={styles.statLabel}>个</span>
            </div>
            <div className={styles.statCard}>
              <h3>今日营收</h3>
              <p className={styles.statValue}>¥{realTimeData.revenue.toFixed(2)}</p>
              <span className={styles.statLabel}>元</span>
            </div>
            <div className={styles.statCard}>
              <h3>系统负载</h3>
              <p className={styles.statValue}>{realTimeData.systemLoad.toFixed(1)}%</p>
              <div className={styles.progressBar}>
                <div 
                  className={styles.progressFill} 
                  style={{ width: `${realTimeData.systemLoad}%` }}
                ></div>
              </div>
            </div>
          </div>
        </section>

        {/* 股票行情 */}
        <section className={styles.stockSection}>
          <h2>股票行情</h2>
          <div className={styles.stockTable}>
            <div className={styles.stockHeader}>
              <span>股票代码</span>
              <span>当前价格</span>
              <span>涨跌额</span>
              <span>涨跌幅</span>
            </div>
            {stockData.map((stock) => (
              <div key={stock.symbol} className={styles.stockRow}>
                <span className={styles.stockSymbol}>{stock.symbol}</span>
                <span className={styles.stockPrice}>${stock.price.toFixed(2)}</span>
                <span className={`${styles.stockChange} ${stock.change >= 0 ? styles.positive : styles.negative}`}>
                  {stock.change >= 0 ? '+' : ''}{stock.change.toFixed(2)}
                </span>
                <span className={`${styles.stockChangePercent} ${stock.changePercent >= 0 ? styles.positive : styles.negative}`}>
                  {stock.changePercent >= 0 ? '+' : ''}{stock.changePercent.toFixed(2)}%
                </span>
              </div>
            ))}
          </div>
        </section>

        {/* 实时聊天 */}
        <section className={styles.chatSection}>
          <h2>实时客服聊天</h2>
          <div className={styles.chatContainer}>
            <div className={styles.chatMessages}>
              {chatMessages.map((msg) => (
                <div key={msg.id} className={`${styles.message} ${msg.user === '我' ? styles.myMessage : styles.otherMessage}`}>
                  <div className={styles.messageHeader}>
                    <span className={styles.messageUser}>{msg.user}</span>
                    <span className={styles.messageTime}>{msg.time}</span>
                  </div>
                  <div className={styles.messageContent}>{msg.message}</div>
                </div>
              ))}
            </div>
            <div className={styles.chatInput}>
              <input
                type="text"
                value={newMessage}
                onChange={(e) => setNewMessage(e.target.value)}
                placeholder="输入消息..."
                onKeyPress={(e) => e.key === 'Enter' && sendMessage()}
              />
              <Button appName="web" onClick={sendMessage}>发送</Button>
            </div>
          </div>
        </section>

        {/* 渲染信息 */}
        <section className={styles.renderInfo}>
          <h3>页面渲染信息</h3>
          <div className={styles.renderDetails}>
            <p><strong>渲染模式:</strong> CSR (Client-Side Rendering)</p>
            <p><strong>客户端渲染时间:</strong> {renderTime.toLocaleString()}</p>
            <p><strong>说明:</strong> 此页面在客户端渲染，支持实时交互和动态更新</p>
            <p><strong>状态管理:</strong> 使用 React useState 和 useEffect</p>
          </div>
        </section>
      </main>

      <footer className={styles.footer}>
        <Link href="/">
          <Button appName="web">返回首页</Button>
        </Link>
      </footer>
    </div>
  );
}
